var validator;
var $goodsAddForm = $("#goods-add-form");
var $tgaUpload;
$(function() {
	validateRule();
	createTypeTree();
	createUploader();

    $("#goods-add .btn-save").click(function() {
    	$tgaUpload.upload();
    });

    $("#goods-add .btn-close").click(function() {
        $("#goods-add-modal-title").html('新增商品');
        closeModal();
    });

});

function _submit(){
	var name = $("#goods-add .btn-save").attr("name");
    getType();
    var validator = $goodsAddForm.validate();
    var flag = validator.form();
    if (flag) {
        if (name == "save") {
            $.post(ctx + "shopping/goods/add", $goodsAddForm.serialize(), function(r) {
                if (r.code == 0) {
                    closeModal();
                    $MB.n_success(r.msg);
                    $MB.refreshTable("goodsTable");
                } else $MB.n_danger(r.msg, '.modal');
            });
        }
        if (name == "update") {
            $.post(ctx + "shopping/goods/update", $goodsAddForm.serialize(), function(r) {
                if (r.code == 0) {
                    closeModal();
                    $MB.n_success(r.msg);
                    $MB.refreshTable("goodsTable");
                } else $MB.n_danger(r.msg, '.modal');
            });
        }
    }
}


function validateRule() {
    var icon = "<i class='zmdi zmdi-close-circle zmdi-hc-fw'></i> ";
    validator = $goodsAddForm.validate({
        rules: {
            name: {
                minlength: 0,
                maxlength: 400,
            },
            price: {
                minlength: 0,
                maxlength: 10,
            },
            pic: {
                minlength: 0,
                maxlength: 800,
            },
            info: {
                minlength: 0,
                maxlength: 65535,
            },
        },
        errorPlacement: function(error, element) {
            if (element.is(":checkbox") || element.is(":radio")) {
                error.appendTo(element.parent().parent());
            } else {
                error.insertAfter(element);
            }
        },
        messages: {
            name: {
                minlength: icon + "长度0到400个字符",
                maxlength: icon + "长度0到400个字符",
            },
            price: {
                minlength: icon + "长度0到10个字符",
                maxlength: icon + "长度0到10个字符",
            },
            pic: {
                minlength: icon + "长度0到800个字符",
                maxlength: icon + "长度0到800个字符",
            },
            info: {
                minlength: icon + "长度0到65535个字符",
                maxlength: icon + "长度0到65535个字符",
            },
        }
    });
}

function closeModal() {
	$("#goods-add-button").attr("name", "save");
    validator.resetForm();
    $MB.closeAndRestModal("goods-add");
    $MB.refreshJsTree("typeTree", createTypeTree());
    //清空队列
    $tgaUpload.reset();
    $(".upload-ul").find(".diyUploadHover").remove();
}

function createTypeTree() {
    $.post(ctx + "shopping/type/tree", {}, function(r) {
        if (r.code == 0) {
            var data = r.msg;
            $('#typeTree').jstree({
                "core": {
                    'data': data.children,
                    'multiple': true
                },
                "state": {
                    "disabled": true
                },
                "checkbox": {
                    "three_state": false
                },
                "plugins": ["wholerow", "checkbox"]
            });
        } else {
            $MB.n_danger(r.msg);
        }
    })
}

function getType() {
    var ref = $('#typeTree').jstree(true);
    $goodsAddForm.find("[name='parentId']").val(ref.get_checked());
}

function createUploader(){
	//上传图片
	$tgaUpload = $('#goodsUpload').diyUpload({
		url: ctx+'upload',
		success:function(data) {
			if(data.code==0){
				var path = data.msg;
				var filename = data.filename;
				
				$goodsAddForm.find("img[imgname='"+filename+"']").attr("src",path);
				
				var source_paths = $goodsAddForm.find("[name='pic']").val();
				source_paths += path+";";
				$goodsAddForm.find("[name='pic']").val(source_paths);
			}
		},
		error:function( err ) { $MB.n_danger(err); },
		buttonText : '',
		accept: {
			title: "Images",
			extensions: 'gif,jpg,jpeg,bmp,png'
		},
		finish: function(){
			//重置值的顺序
			var imgs = $(".upload-pick").parent().find("img");
	    	var value = "";
	    	$(imgs).each(function(i,item){
	    		value += $(item).attr("src") + ";";
	    	})
	    	$(".upload-pick").parent().next("[type='hidden']").val(value);
			_submit();
		},
		thumb:{
			width:120,
			height:90,
			quality:100,
			allowMagnify:true,
			crop:true,
			type:"image/jpeg"
		}
	});
}